package com.bbcare.nutritious.plat.service.imp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.nutritious.plat.entity.PtBloodsugarRecord;
import com.bbcare.nutritious.plat.entity.PtWeight;
import com.bbcare.nutritious.plat.service.IWeightService;
import com.bbcare.nutritious.plat.store.ibatis.IWeightDao;

/**
 * 体重数据接口
 * @modify:
 *
 */
@Service
public class WeightService implements IWeightService {

	public static final Logger logger = Logger.getLogger(WeightService.class);

    @Autowired
    private IWeightDao weightDao;
   /**
    * 保存或修改孕妇体重数据
    */
    @Override
	public Map<String, Object> saveWeight(PtWeight weight) throws Exception {
    	//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在某租户下
    	String tenantId = weightDao.getUserTenantIdByUserId(weight.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	weight.setTenantId(tenantId);
    	String nowTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
    	//保存孕妇体重信息,如果id存在则修改,不存在则添加
    	if(StringUtils.isEmpty(weight.getId())){
    		//判断该天信息是否存在
        	int total = weightDao.countByUseridAndDate(weight);
        	if(total>0){
        		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"新增失败,该条数据已存在");
        	}
    		//生成id
    		String id = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_WEIGHT_ID);
    		weight.setId(id);
    		weight.setLastUpdate(nowTime);
    		weightDao.saveWeight(weight);
    	}else{
    		weight.setLastUpdate(nowTime);
    		weightDao.updateWeight(weight);
    		//保存历史
    		weight.setUpdateType(Constants.HANDLE_TYPE_CHANGE);
    		weightDao.saveWeightHis(weight);
    	}
    	rspMap.put("weight", weight);
		return rspMap;
	}
    /**
     * 删除孕妇体重数据
     */
     @Override
 	public Map<String, Object> delWeightById(String id) throws Exception {
     	//创建线程安全的hashmap返回对象
     	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
     	//查询用户体重信息
     	PtWeight weight = new PtWeight();
     	weight.setId(id);
     	List<PtWeight> list = weightDao.listWeightByIdAndDate(weight);
     	if(CollectionUtils.isEmpty(list)){
     		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"该条数据已删除,请勿重复操作");
     	}
     	weight = list.get(0);
     	//删除体重信息
     	weightDao.deleteyId(id);
     	//保存删除记录
     	weight.setLastUpdate(DateUtil.getTimeString(DateUtil.getSysDateA()));
 		weight.setUpdateType(Constants.HANDLE_TYPE_DELETE);
 		weightDao.saveWeightHis(weight);
 		return rspMap;
 	}
    /**
     * 通过id,userid,日期 条件查询孕妇体重数据
     */
	@Override
	public Map<String, Object> listWeightByIdAndDate(PtWeight weight) {
		//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在
    	String tenantId = weightDao.getUserTenantIdByUserId(weight.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	List<PtWeight> list = weightDao.listWeightByIdAndDate(weight);
    	if(!CollectionUtils.isEmpty(list)){
    		for (int i = 0; i < list.size(); i++) {
    			list.get(i).setLastUpdate(DateUtil.getTimeStampSec(list.get(i).getLastUpdate()));
    		}
    	}
    	rspMap.put("weightList", list);
		return rspMap;
	}
	/**
     * 根据userid+testDate或id查询用户所属租户接口实现(返回实体)
     */
	@Override
	public Map<String, Object> getWeight(PtWeight weight) {
		//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在
    	if(StringUtils.isEmpty(weight.getId())){
    		String tenantId = weightDao.getUserTenantIdByUserId(weight.getUserId());
    		if(StringUtils.isEmpty(tenantId)){
        		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
        	}
    	}
    	List<PtWeight> list = weightDao.listWeightByIdAndDate(weight);
    	if(CollectionUtils.isEmpty(list)){
    		rspMap.put("isBack", false);
    		rspMap.put("weight", new PtBloodsugarRecord());
     	}else{
     		list.get(0).setLastUpdate(DateUtil.getTimeStampSec(list.get(0).getLastUpdate()));
     		rspMap.put("weight", list.get(0));
     		rspMap.put("isBack", true);
     	}
		return rspMap;
	}
	/**
     * 获取体重图表数据
     * 日期-体重数据分析
     * 可以根据日期参数进行调整
     * @param weight
     * @return
     */
	@Override
	public Map<String, Object> getWeightChartData(PtWeight weight) {
		//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在
    	String tenantId = weightDao.getUserTenantIdByUserId(weight.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	List<PtWeight> list = weightDao.listWeightByIdAndDate(weight);
    	//图表显示的体重和日期数据的拼接
    	rspMap.put("list", list);
		return rspMap;
	}
	/**
	 * 查询需要导出的体重数据
	 * @param weight
	 * @return
	 */
	@Override
	public List<PtWeight> exportWeightData(PtWeight weight) {
    	//判断该用户是否存在
    	String tenantId = weightDao.getUserTenantIdByUserId(weight.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	List<PtWeight> list = weightDao.listExportWeightData(weight);
    	//图表显示的体重和日期数据的拼接
    	List<String> Chartdate = Collections.synchronizedList(new ArrayList<String>());
    	List<String> ChartweightNum = Collections.synchronizedList(new ArrayList<String>());
    	if(!CollectionUtils.isEmpty(list)){
    		for (int i = 0; i < list.size(); i++) {
    			Chartdate.add(list.get(i).getTestDate());
    			ChartweightNum.add(list.get(i).getWeightNumber());
    		}
    	}
		return list;
	}
	/**
	 * 分页查询
	 */
	@Override
	public Map<String, Object> listWeightForPage(PtWeight weight) {
		//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在
    	String tenantId = weightDao.getUserTenantIdByUserId(weight.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	//体重分页数据
    	List<PtWeight> list = weightDao.listWeightForPage(weight);
    	//统计数据总量
    	int totalCount = weightDao.countWeight(weight);
    	//处理mysql的timestemp格式问题
    	if(!CollectionUtils.isEmpty(list)){
    		for (int i = 0; i < list.size(); i++) {
    			list.get(i).setLastUpdate(DateUtil.getTimeStampSec(list.get(i).getLastUpdate()));
    		}
    	}
    	rspMap.put("list", list);
    	rspMap.put("totalCount", totalCount);
		return rspMap;
	}
	/**
	 * 根据userid查询用户所属租户
	 * @param userId 用户id
	 */
	@Override
	public String getUserTenantIdByUserId(String userId){
		return weightDao.getUserTenantIdByUserId(userId);
	}
}
